using System;
using System.Collections.Generic;


namespace ODX.Core
{
    internal class WeakEntityStorage
    {
        private Dictionary<string, WeakReference> ents = new Dictionary<string, WeakReference>();

        internal Entity this[string ID]
        {
            get
            {
                WeakReference wr;
                if ( ! ents.TryGetValue(ID, out wr) )
                    return null;

                if ( wr == null )
                    return null;

                if ( wr.Target != null )
                    return wr.Target as Entity;

                ents.Remove(ID);
                return null;
            }
            set
            {
                if ( value == null )
                    return;

                ents[value.ID] = new WeakReference(value, false);
            }
        }

        internal Entity[] All
        {
            get
            {
                List<Entity> all = new List<Entity>();
                List<string> keysToRemove = new List<string>();

                foreach ( KeyValuePair<string, WeakReference> kv in ents )
                {
                    if (kv.Value.Target != null)
                        all.Add(kv.Value.Target as Entity);
                    else
                        keysToRemove.Add(kv.Key);
                }

                foreach (string key in keysToRemove)
                    ents.Remove(key);

                return all.ToArray();
            }
        }
    }
}
